package io.wongxd.solution.compose.photo.ui.picker

import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalView
import io.wongxd.solution.compose.photo.data.MediaPhotoBucketAllId
import io.wongxd.solution.compose.photo.ui.edit.EditBox
import io.wongxd.solution.compose.photo.ui.edit.EditState
import io.wongxd.solution.compose.photo.ui.saveEditBitmapToStore
import io.wongxd.solution.compose.photo.vm.PhotoPickerViewModel
import kotlinx.coroutines.launch

@Composable
fun PhotoPickerEditPage(
    viewModel: PhotoPickerViewModel,
    id: Long
) {
    val item = remember(id) {
        viewModel.photoPickerDataFlow.value.data
            ?.find { it.id == MediaPhotoBucketAllId }
            ?.list
            ?.find { it.model.id == id }
    }
    if (item != null) {
        val view = LocalView.current
        val scope = rememberCoroutineScope()
        val config = LocalPhotoPickerConfig.current.editConfig
        val editState = remember(config) {
            EditState(config)
        }
        EditBox(
            photoProvider = item.photoProvider,
            state = editState,
            onBack = {
                viewModel.pop()
            }
        ) { drawable, editLayers ->
            if (editLayers.isEmpty()) {
                viewModel.pop()
                return@EditBox
            }
            scope.launch {
                view.saveEditBitmapToStore(
                    drawable,
                    editLayers,
                    "edit-${System.currentTimeMillis()}",
                    view.width
                )
                viewModel.loadData()
                viewModel.pop()
            }
        }
    }
}
